package com.ydj.framework.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrossFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        res.setContentType(MediaType.APPLICATION_JSON_VALUE);
        String origin = req.getHeader("Origin");
        res.setHeader("access-Control-Allow-Origin", StringUtils.isBlank(origin) ? "*" : origin);
        res.setHeader("access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("access-Control-Max-Age", "1800");
        res.setHeader("access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-type, X-E4M-With,userId, Authorization");
        res.setHeader("access-Control-Allow-Credentials", "true");
        res.setHeader("XDomainRequestAllowed", "1");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}